<template>
  <div class="public_editor_container">
    <div class="public_editor_setting">
        <div class="editor_setting_title">
            <div class="title">
                {{worksheetInfo.name}}
                <a-switch v-model="enabled" @change="onStartChange" checked-children="启动" un-checked-children="关闭"/>
            </div>
            <a-button size="small" shape="round" @click="save">
                完成
            </a-button>
        </div>
        <div class="editor_des">启用后，将表单公开发布给应用外的用户填写，为你的工作表收集数据</div>
        <template v-if="enabled">
            <div class="public_editor_field">
                <div class="title">
                    设置公开链接
                </div>
                <div class="editor_link">
                    <a-tooltip placement="top">
                        <template slot="title">
                            <span>{{url}}</span>
                        </template>
                        <div class="link_inner editor_inner">
                            {{url}}
                        </div>
                    </a-tooltip>
                    <a-tooltip placement="bottom">
                        <template slot="title">
                            <span>复制</span>
                        </template>
                        <div class="button_inner editor_inner"
                            v-clipboard:copy="url"
                            v-clipboard:success="handleCopyOk"
                            v-clipboard:error="handleCopyErr"
                        >
                            <a-icon type="copy" />
                        </div>
                    </a-tooltip>
                    <a-popover placement="bottom">
                        <template slot="content">
                            <div class="editor_qrcode" @click="downQrcodeClick">
                                <img :src="qrcodeUrl(this.qrcode)"/>
                                <a :href="qrcodeUrl(this.qrcode)" download><span>下载</span></a>
                            </div>
                        </template>
                        <div class="button_inner editor_inner">
                            <a-icon type="qrcode" />
                        </div>
                    </a-popover>
                    <a-tooltip placement="bottom">
                        <template slot="title">
                            <span>重新生成链接</span>
                        </template>
                        <div class="button_inner editor_inner" @click="updateUrlClcik">
                            <a-icon type="sync" />
                        </div>
                    </a-tooltip>
                </div>
                
                <!-- 设置表单参数 -->
                <el-button type="primary" @click="dialogFormVisible = true">发布设置</el-button>
                <el-dialog title="扩展参数" :visible.sync="dialogFormVisible" width="600px" :modal-append-to-body="false">
                    <el-form :model="form">
                        <el-form-item label="文本字段" label-width="120px">
                        <el-select v-model="form.textId" placeholder="请选择" @change="textId_change">
                            <el-option v-for="(item, index) in filter_config" :key="index" :label="item.options.label" :value="item.name"></el-option>
                        </el-select>
                        </el-form-item>
                        <el-form-item label="参数" label-width="120px">
                            <el-input v-model="form.param" style="width: 226px" placeholder="输入参数"></el-input>
                        </el-form-item>
                    </el-form>
                    <div class="dialog-button" style="top: 85px">
                        <el-button type="primary" @click="show_form">恢复隐藏</el-button>
                    </div>
                    <div class="dialog-button">
                        <el-button type="primary" @click="craeat_address">生成地址</el-button>
                    </div>
                    <!-- 设置的扩展参数地址展示 -->
                    <div style="margin-top: 10px;" v-for="(item,index) in address_arr" :key="index">
                        <div class="show_address" :title="item.name" style="width: 100px">{{item.param}}</div>
                        <div class="show_address" :title="item.url" style="width: 330px">{{item.url}}</div>
                        <!-- 复制 -->
                        <a-tooltip placement="bottom">
                            <template slot="title">
                                <span>复制</span>
                            </template>
                            <div class="button_inner editor_inner"
                                v-clipboard:copy="item.url"
                                v-clipboard:success="handleCopyOk"
                                v-clipboard:error="handleCopyErr"
                            >
                                <a-icon type="copy" />
                            </div>
                        </a-tooltip>
                        <!-- 下载 -->
                        <a-popover placement="bottom">
                            <template slot="content">
                                <div class="editor_qrcode" @click="downQrcodeClick">
                                    <img :src="qrcodeUrl(item.qrcode)"/>
                                    <a :href="qrcodeUrl(item.qrcode)" download><span>下载</span></a>
                                </div>
                            </template>
                            <div class="button_inner editor_inner">
                                <a-icon type="qrcode" />
                            </div>
                        </a-popover>
                        <!-- 删除 -->
                        <div class="del_address" @click="del_form(item.url)">
                            <a style="color: red">删除</a>
                        </div>
                    </div>
                </el-dialog>

                <div class="editor_fillTimes">
                    <span>标题</span>
                    <div>
                        <a-input v-model="title" @blur="onTitleChange"/>
                    </div>
                </div>
                <div class="editor_fillTimes">
                    <span>填报次数</span>
                    <div>
                        <a-radio-group v-model="fillTimes" @change="onFillTimesChange">
                            <a-radio :style="radioStyle" :value="0">
                                无限制
                            </a-radio>
                            <a-radio :style="radioStyle" :value="1">
                                仅一次
                            </a-radio>
                            <a-radio :style="radioStyle" :value="2">
                                每天一次
                            </a-radio>
                        </a-radio-group>
                    </div>
                </div>
            </div>
            <!-- <div class="public_editor_field flex_all">
                <div class="title">
                    字段
                </div>
                <div class="editor_field_container flex_all">
                    <div class="field_body">
                        <div class="field_item editor_inner"
                            v-for="field in fields"
                            :key="field.name"
                        >
                            <span>{{field.alia}}</span>
                            <a-icon class="bt_plus" type="plus" />
                        </div>
                    </div>
                </div>
            </div> -->
        </template>
    </div>
    <div class="public_editor_form" v-if="enabled">
        <div class="public_form_body">
            <div class="form_header">{{title}}</div>
            <div class="form_body">
                <v-form-render :form-json="formJson" :form-data="formData" :option-data="optionData" ref="vFormRef" class="cgs-vformRender"></v-form-render>
            </div>
        </div>
    </div>
  </div>
</template>

<script>
import {getWorksheetPublicDetail, updateWorksheetPublic, addWorksheetPublic, deleteWorksheetPublic} from '@/api/worksheet'
import { DataType } from '@/filterConstant'
import {uuid} from '@/utils/utils'
export default {
    data(){
        return {
            enabled: false,
            worksheetInfo: {},
            url: '',
            qrcode: '',
            shareId: '',
            title: '',
            fillTimes: 0,
            fieldSetting: {},
            addFields: [],
            radioStyle: {
                display: 'block',
                height: '30px',
                lineHeight: '30px',
            },

            formJson: {},
            formData: {},
            optionData: {},
            // 扩展参数相关
            config: {},
            form: {
                param: '',
                textId: '',
            },
            dialogFormVisible: false,
            address_arr: [],
        }
    },
    methods:{
        save(){
            this.$router.back()
        },
        qrcodeUrl(qrcode) {
            return `${window.location.origin}/file/${qrcode}`;
        },
        addField(item){
        },
        updateUrlClcik(){
            this.$confirm("如果您选择生成新链接，则旧链接将不再可用", "确认生成新链接吗？", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
            .then(async () => {
                let id = uuid()
                this.shareId = id
                this.url = `${window.location.origin}/public/form/${id}`
                const { url, shareId} = this
                await updateWorksheetPublic({
                    worksheetId: this.worksheetId,
                    shareId,
                    url,
                })
                let data = await getWorksheetPublicDetail({worksheetId: this.worksheetId})
                const {qrcode} = data
                this.qrcode = qrcode
            })
        },
        async onStartChange(enabled){
            let {worksheetInfo} = this
            await updateWorksheetPublic({
                worksheetId: this.worksheetId,
                enabled
            })
            if(enabled){
                let config = JSON.parse(worksheetInfo.config);
                this.config = config
                this.$refs.vFormRef.setFormJson(config)
            }
        },
        async onTitleChange(){
            let {title} = this
            await updateWorksheetPublic({
                worksheetId: this.worksheetId,
                title
            })
        },
        async onFillTimesChange(enabled){
            let {fillTimes} = this
            await updateWorksheetPublic({
                worksheetId: this.worksheetId,
                fillTimes
            })
        },
        downQrcodeClick(){

        },
        handleCopyOk(){
            this.$message.success('复制成功');
        },
        handleCopyErr(){
            this.$message.error('复制失败');
        },
        // 生成扩展参数地址
        async craeat_address() {
            if(this.form.param && this.form.textId){
                let parms = {
                    id: uuid(),
                    param: this.form.param,
                    url: this.url + '?source=' + this.form.param
                }

                let address = await addWorksheetPublic({
                    param: parms.param,
                    url: parms.url,
                    worksheetId: this.worksheetId,
                })
                this.address_arr.push(address)
            }else{
                alert("请填写完整")
            }
        },

        // 恢复隐藏
        async show_form() {
            let data = await getWorksheetPublicDetail({worksheetId: this.worksheetId})
            const {worksheetInfo} = data
            this.worksheetInfo = worksheetInfo
            let config = JSON.parse(worksheetInfo.config);
            this.config = config
            this.$refs.vFormRef.setFormJson(this.config)
        },

        // 删除扩展地址参数
        async del_form(url) {
            let data = await getWorksheetPublicDetail({worksheetId: this.worksheetId})
            const {extParam} = data
            for(const item in extParam.extUrls){
                if(url == extParam.extUrls[item].url){
                    await deleteWorksheetPublic({
                        id: extParam.extUrls[item].id
                    })
                    this.address_arr.splice(item, 1)
                }
            }
        },
        async textId_change() {
            await updateWorksheetPublic({
                worksheetId: this.worksheetId,
                extParam: {
                    extField: this.form.textId
                }
            })
        },
    },
    computed:{
        worksheetId() {
            return this.$route.params.worksheetId;
        },
        fields() {
            let fields = []
            if(this.worksheetInfo?.fields){
                // for (const key in this.fieldSetting) {
                //     const element = this.fieldSetting[key];
                //     if(!element){
                //         let field = this.worksheetInfo?.fields.find(f => f.name === key)
                //         if(field){
                //             fields.push(field)
                //         }
                //     }
                // }
                fields = this.worksheetInfo?.fields
            }
            return fields;
        },
        // 过滤文本字段
        filter_config() {
            let new_config = this.worksheetInfo?.fields.filter(f => (f.dataType === DataType.TEXT || f.dataType === DataType.TEXT_AREA)) || []
            
            return new_config
        }
    },
    async mounted(){
        let data = await getWorksheetPublicDetail({worksheetId: this.worksheetId})
        const {qrcode, url, worksheetInfo, enabled, shareId, title, fillTimes, fieldSetting, extParam} = data
        this.worksheetInfo = worksheetInfo
        let config = JSON.parse(worksheetInfo.config);
        this.config = config
        
        if(extParam){
            this.form.textId = extParam?.extField || ''
            this.address_arr = extParam.extUrls || []
        }
        let isFirst = qrcode === '' && url === ''
        if(isFirst){
            let id = uuid()
            await updateWorksheetPublic({
                worksheetId: this.worksheetId,
                shareId: id,
                url: `${window.location.origin}/public/form/${id}`,
                enabled: false,
                title: '未命名表单'
            })
            let data = await getWorksheetPublicDetail({worksheetId: this.worksheetId})
            const {qrcode, url, enabled, shareId, title, fillTimes, fieldSetting} = data
            this.enabled = enabled
            this.url = url
            this.qrcode = qrcode
            this.shareId = shareId
            this.title = title === "" ? '未命名表单' : title
            this.fillTimes = fillTimes
            if(!fieldSetting){
                let obj = {}
                for (const key in worksheetInfo.fields) {
                    const element = worksheetInfo.fields[key];
                    obj[element.name] = false
                }
                this.fieldSetting = obj
            }else {
                this.fieldSetting = fieldSetting
            }
        } else {
            this.enabled = enabled
            this.url = url
            this.qrcode = qrcode
            this.shareId = shareId
            this.title = title === "" ? '未命名表单' : title
            this.fillTimes = fillTimes
            if(enabled){
                this.$nextTick(() => {
                    // let config = JSON.parse(worksheetInfo.config);
                    this.$refs.vFormRef.setFormJson(this.config)
                })
            }
            if(!fieldSetting){
                // let obj = {}
                // for (const key in worksheetInfo.fields) {
                //     const element = worksheetInfo.fields[key];
                //     obj[element.name] = false
                // }
                // this.fieldSetting = obj
            }else {
                this.fieldSetting = fieldSetting
            }
        }
    }
}
</script>

<style lang="less">
.public_editor_container{
    width: 100%;
    height: 100%;
    display: flex;
    background-color: #f3faff;

    .public_editor_setting{
        z-index: 2;
        width: 350px;
        box-shadow: 0 4px 8px rgb(0 0 0 / 16%);
        background-color: #fff;
        padding: 20px;
        display: flex;
        flex-direction: column;

        .editor_setting_title{
            display: flex;
            align-items: center;
            justify-content: space-between;
            .title{
                color: rgb(51, 51, 51);
                font-weight: bold;
                font-size: 18px;
            }
        }

        .editor_des{
            font-size: 13px;
            color: #9e9e9e;    
            margin: 10px 0;
            line-height: 18px;
        }
    }

    .public_editor_form{
        flex: 1 1 auto;
        overflow-y: auto;

        .public_form_body{
            width: 800px;
            margin: 50px auto 20px;
            border-radius: 3px;
            background-color: #fff;
            box-shadow: 0 1px 4px rgb(0 0 0 / 16%);

            .form_header{
                padding: 10px 20px 20px;
                border-bottom: 1px solid rgb(0 0 0 / 16%);
                color: #333;
                font-size: 36px;
                font-weight: 500;
            }
            .form_body{
                padding: 20px 50px;
            }
        }
        
    }

    .public_editor_field{
        margin-top: 15px;
        display: flex;
        flex-direction: column;
        position: relative;

        .title{
            color: rgb(117, 117, 117);
            font-weight: bold;
            font-size: 14px;
        }

        .editor_inner{
            border-radius: 3px;
            height: 36px;
            line-height: 36px;
            background-color: rgb(241, 241, 241);
            color: rgb(51, 51, 51);
            font-size: 14px;
            padding: 0px 10px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: inline-block;
        }

        .show_address{
            // display: block;
            border-radius: 3px;
            height: 36px;
            line-height: 36px;
            background-color: rgb(241, 241, 241);
            color: rgb(51, 51, 51);
            font-size: 14px;
            padding: 0px 10px;
            margin-right: 10px;
            display: inline-block;
            position: relative;
            white-space: nowrap;
            overflow:hidden;
            text-overflow: ellipsis;
        }

        .del_address{
            position: relative;
            bottom: 15px;
            left: 10px;
            display: inline-block
        }

        .editor_link{
            margin-top: 10px;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;

            .link_inner{
                flex-shrink: 0;
                width: 200px;
            }
        }

        .button_inner{
            cursor: pointer;
        }
        .button_inner:hover{
            color: #00aaff;
        }

        .editor_fillTimes{
            padding: 10px 0 0 0;

            span{
                font-weight: bold;
                color: rgb(117, 117, 117);
                font-size: 12px;
            }
        }

        .editor_field_container{
            position: relative;

            .field_body{
                position: absolute;
                width: 100%;
                padding: 10px 20px 10px 0;
                top: 10px;
                bottom: 0px;
                overflow-y: auto;
            }

            .field_item{
                width: 100%;
                padding: 0 20px;
                margin-bottom: 10px;
                display: flex;
                justify-content: space-between;
                align-items: center;

                .bt_plus{
                    cursor: pointer;
                }
                .bt_plus:hover{
                    color: #00aaff;
                }
            }
        }

        .dialog-button{
            position: absolute;
            right: 100px;
            top: 145px;
        }
    }

    .flex_all{
        flex: 1 1 auto;
    }
}

.editor_qrcode{
    display: flex;
    flex-direction: column;
    align-items: center;
}
</style>